#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/1/23 11:37
# @Author  : Wang Feng
# @FileName: testtask.py
# @Software: PyCharm
from flask import Blueprint, request, jsonify

from app.models import TestTask, TestResult
from app.utils.jenkins_excute import is_job_no_in_queue, get_last_build_job, get_build_info
from app.utils.response_code import RET

testtask = Blueprint('testtask', __name__)


@testtask.route('/list', methods=['POST'])
def list_testtask():
    """
    查询测试任务列表
    :return:
    """
    task_name = request.form.get('task_name', type=str)
    result = request.form.get('result', type=str)
    page_num = request.form.get('page_num', 1, type=int)
    page_size = request.form.get('page_size', 10, type=int)

    filter_list = []
    if task_name:
        filter_list.append(TestTask.task_name.contains(task_name))
    if result:
        filter_list.append(TestTask.result.contains(result))

    pagination = TestTask.query.filter(
        *filter_list
    ).order_by(TestTask.id.desc()).paginate(page=page_num, per_page=page_size)
    total_page = pagination.pages
    count = pagination.total
    testtasks = pagination.items
    data = list(map(lambda testtask: testtask.to_dict(), testtasks))
    for testtask in data:
        testtask['total_num'] = TestResult.query.filter(TestResult.taskId == testtask['task_id']).count()
        testtask['success_num'] = TestResult.query.filter(TestResult.taskId == testtask['task_id'],
                                                        TestResult.status == 'passed').count()
        if testtask['total_num'] == 0:
            testtask['rate'] = 0
        else:
            rate = testtask['success_num'] / testtask['total_num'] * 100
            testtask['rate'] = str(int(rate) if rate % 1 == 0 else round(rate, 2)) + '%'

    # print(data)
    return jsonify(code=RET.OK, msg='查询成功', total_page=total_page, count=count, data=data)


@testtask.route('/refresh', methods=['POST'])
def refresh():
    task_id = request.form.get('task_id')
    print(task_id)
    if not task_id:
        return jsonify(code=RET.PARAMERR, msg='参数错误: task_id不能为空')
    else:
        # 查找数据库中对应的task_id数据
        testtask = TestTask.query.filter_by(task_id=task_id).first()
        if testtask is None:
            return jsonify(code=RET.NODATA, msg='数据不存在')
        else:
            # 如果job_no在jenkins队列中
            if is_job_no_in_queue(task_id):
                # 如果存在更新状态为pending
                testtask.result = 'pending'
                if not testtask.save():
                    return jsonify(code=RET.DBERR, msg='状态更新失败')
                    # 如果job_no不在jenkins队列中, 说明已经进入build阶段
            else:
            # print(type(testtask.duration))
                # 如果任务状态为pending
                if testtask.result in ('pending', 'executing') or (
                        int(testtask.duration) == 0):
                    # 获取build_name
                    builds = get_last_build_job('public_test', 10)
                    print(builds)
                    for build in builds:
                        build_info = get_build_info('public_test', build, task_id)
                        if build_info:
                            # print(11111111111111111111111111111111111111111111111111111)
                            print(build_info)
                            # print(222222222222222222222222222222222222222222222222222)
                            number, result, duration, timestamp, fullDisplayName = build_info
                            testtask.result = result or 'executing'
                            testtask.duration = duration
                            testtask.timestamp = timestamp
                            testtask.full_display_name = fullDisplayName
                            testtask.total_num = TestResult.query.filter(
                                TestResult.taskId == testtask.task_id).count()
                            testtask.success_num = TestResult.query.filter(TestResult.taskId == task_id,
                                                                           TestResult.status == 'passed').count()
                            if testtask.total_num == 0:
                                testtask.rate = 0
                            else:
                                rate = testtask.success_num / testtask.total_num * 100
                                testtask.rate = str(int(rate) if rate % 1 == 0 else round(rate, 2)) + '%'
                            # print(build_info)
                            # print(testtask)
                            print(number, result, duration, timestamp, fullDisplayName)
                            if not testtask.save():
                                return jsonify(code=RET.DBERR, msg='状态更新失败')
                            return jsonify(code=RET.OK, msg='状态更新成功')
                else:
                    return jsonify(code=RET.DATAERR, msg='数据状态不可更新')
                    # abort(400, msg='数据为不可更新状态')

    return jsonify(code=RET.OK, msg='状态更新成功')

